<style>
  .contentMarginLeft{
    margin-left:10%;margin-right:10%;
  }
</style>
<template>
     <el-card :class="{contentMarginLeft: !isClickEditing}">
       <div slot="header" class="clearfix" v-if="!isClickEditing">
         <span>我的公司</span>
       </div>
       <el-row :gutter="10">
         <el-form ref="companyForm" :model="model" label-position="left" label-width="140px">
           <el-row >
             <el-col :span="24" v-if="isClickEditing">
               <el-form-item label="公司编号:">
                 <span>{{ data.code }}</span>
               </el-form-item>
             </el-col>
             <el-col :span="24" v-if="isClickEditing">
               <el-form-item label="状态:">
                 <span>{{ data.state == 1 ? '启用' : '停用'}}</span>
               </el-form-item>
             </el-col>
             <el-col :span="13">
               <el-form-item prop="name" label="公司名称:"
                             :rules="[
                        {required: true, message: '公司名称必须', trigger: 'blur'},
                        {validator: isChinese, message: '只能输入中文', trigger: 'blur'}
                      ]">
                 <el-input type="text" v-model="model.name" placeholder="公司营业执照名称"></el-input>
               </el-form-item>
             </el-col>
             <el-col :span="13">
               <el-form-item prop="communityCode" label="统一社会信用代码:"
                             :rules="[
                        {required: true, message: '信用代码必须', trigger: 'blur'},
                        {validator: isEnglishOrNumber, message: '只能输入英文字母或数字', trigger: 'blur'},
                        {message: '输入长度不得低于15位数字或字母', trigger: 'blur', min: 15}
                      ]">
                 <el-input type="text" v-model="model.communityCode" placeholder="统一社会信用代码">
                 </el-input>
               </el-form-item>
             </el-col>
             <el-col :span="13">
               <el-form-item prop="legalPerson" label="法定代表人:"
                             :rules="[
                        {required: true, message: '法人姓名必须', trigger: 'blur'},
                        {validator: isChinese, message: '只能输入中文', trigger: 'blur'}
                      ]">
                 <el-input type="text" v-model="model.legalPerson" placeholder="法定代表人">
                 </el-input>
               </el-form-item>
             </el-col>
             <el-col :span="13">
               <el-form-item prop="contactsName" label="公司联系人:"
                             :rules="[
                        {required: true, message: '联系人姓名必须', trigger: 'blur'}
                      ]">
                 <el-input type="text" v-model="model.contactsName" placeholder="公司联系人(业务联系人姓名)">
                 </el-input>
               </el-form-item>
             </el-col>
             <el-col :span="13">
               <el-form-item prop="contactsPhone" label="联系人电话:"
                             :rules="[
                        {required: true, message: '联系电话', trigger: 'blur'},
                        {validator: isPhone, message: '手机号格式不正确', trigger: 'blur'},
                      ]">
                 <el-input type="text" v-model="model.contactsPhone" placeholder="联系人电话(手机号码)">
                 </el-input>
               </el-form-item>
             </el-col>
             <el-col :span="13">
               <el-row :gutter="5">
                 <el-col :span="12">
                   <el-form-item label="公司住所:" prop="addressArr" :rules="[
                    {required: true, message: '公司住所必须', type:'array', trigger: 'change'}
                  ]">
                     <CascadeAddress v-model="model.addressArr" :level="3"/>
                   </el-form-item>
                 </el-col>
                 <el-col :span="12">
                   <el-form-item label-width="0" prop="detailAddress" :rules="[
                    {required: true, message: '详细地址必须', trigger: 'blur'}
                  ]">
                     <el-input :maxlength="200" placeholder="详细地址" v-model="model.detailAddress"/>
                   </el-form-item>
                 </el-col>
               </el-row>
             </el-col>
             <el-col :span="14">
               <el-row :gutter="5" v-for="(item, index) in model.phoneArr" :key="index">
                 <!--新加 公司电话-->
                 <el-col :span="18" style="position:relative;">
                   <el-form-item :label="index === 0 ? '公司服务热线' : ''" :prop="'phoneArr.' + index + '.phone'"
                                 :rules="[
                     {required: true, message: '公司服务热线必须', trigger: 'blur'},
                     {validator: isPhoneOrTel, message: '电话格式不正确', trigger: 'blur'}
                  ]">
                     <el-input v-model="item.phone"></el-input>
                   </el-form-item>
                   <span style="position:absolute;left:20px;top:30px;color:#ff4949;font-size:12px;" v-if="index === 0"> (最多添加4个)</span>
                 </el-col>
                 <el-col :span="6">
                   <el-button type="info" @click="delFee(model.phoneArr, index)">删除</el-button>
                   <el-button @click="addFee" type="primary" v-if="index == model.phoneArr.length - 1">添加</el-button>
                 </el-col>
                 <!--<div class="col-xs-3" v-if="index == 0"><span>（最多添加4个电话号码）</span></div>-->
               </el-row>
             </el-col>
             <el-col :span="24">
               <el-form-item   prop="logoImg" label="Logo:">
                 <!--<uploadImage v-model="model.businessLicense" :formData="{group: '1'}" :max="1" :singleMaxSize="524288"></uploadImage>-->
                 <UploadImage v-model="model.logoImg" :max="1" :formData="{group: '1'}"></UploadImage>
               </el-form-item>
             </el-col>
             <el-col :span="24">
               <el-form-item   prop="businessImg" label="营业执照:"
                               :rules="[
                         {required: true, message: '营业执照必须', trigger: 'change', type: 'array'}
                      ]">
                 <UploadImage v-model="model.businessImg" :max="1" :formData="{group: '1'}"></UploadImage>
               </el-form-item>
             </el-col>
             <el-col :span="24" v-if="isTrunkUser == 1 || isNotGavePower == 1 || isNotGavePower == 2">
               <el-form-item   prop="roadImg" label="道路运输许可证:"
                               :rules="[
                         {required: true, message: '道路运输许可证必须', trigger: 'change', type: 'array'}
                      ]">
                 <UploadImage v-model="model.roadImg" :max="1" :formData="{group: '1'}"></UploadImage>
               </el-form-item>
             </el-col>
             <el-col :span="3" :offset="2" v-if="isClickEditing">
               <el-button type="info" class="btn-block" style="width:100%" @click="emitIsClickEditing"> 取消</el-button>
             </el-col >
             <el-col :span="3" :offset="2">
               <el-button type="primary" class="btn-block" style="width:100%" @click="submit" :loading="loading"> 确定</el-button>
             </el-col>
           </el-row>
         </el-form>
       </el-row>
     </el-card>
</template>
<script>
import {dotData, copy, confirm, alert} from '@/utils'
import {getTempToken, onlyLoginOut} from '@/utils/auth'
import {isChinese, isEnglishOrNumber, isPhone, isInteger, isPhoneOrTel} from '@/utils/validate'
export default {
  name: '',
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    // 是否是我的公司--点击编辑进来的
    isClickEditing: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '公司信息'
    }
  },
  data() {
    return {
      isNotGavePower: this.$route.query.isNotGavePower, // 是否是 未授权进来的修改资质页面
      userId: this.$route.query.userId,
      userPhone: this.$route.query.userPhone,
      // isEditing: false,
      isTrunkUser: 0, // 是否是物流端的账号：1 是：就要显示道路证和提交道路证
      httpData: {},
      loading: false,
      model: {
        name: '',
        communityCode: '',
        legalPerson: '',
        phoneArr: [ // 服务热线（多个）
          { phone: '' }
        ],
        addressArr: [],
        detailAddress: '',
        contactsName: '',
        contactsPhone: '',
        logoImg: [],
        businessImg: [],
        roadImg: []
      }
    }
  },
  created() {
    // 若 不是我的公司页面点击进来的（审核未通过后进来的编辑），则直接请求table数据
    if (!this.isClickEditing) {
      if (this.isNotGavePower === 2) { // 2：从资料未填写完整、或 审核未通过 而来
        this.getData()
      }
    } else { // 我的公司点'编辑'进来的
      this.showForm(this.data)
      this.isTrunkUser = dotData(this.data, 'isTrunk')
    }
  },
  methods: {
    isInteger,
    isPhone,
    isChinese,
    isEnglishOrNumber,
    isPhoneOrTel,
    // 这个是审核未通过后进来的 修改我的公司
    getData() {
      // 取出omsLogin里:假登录存到缓存里的token，请求接口要用
      let token = getTempToken()
      console.log('22222', token)
      this.$ajax.get('/ms-warehouse-order/basicData/findMyCompanyInfo', undefined, {token}).then(response => {
        let success = dotData(response, 'success')
        this.isTrunkUser = dotData(response, 'data.isTrunk') // 是否是物流端的用户 再次提交--> 1是 才显示 表单项：提交道路许可证
        console.log('这个是审核未通过后进来的 修改我的公司', this.isTrunkUser, 'typeof', typeof this.isTrunkUser)
        console.log('this.isNotGavePower', this.isNotGavePower, 'typeof', typeof this.isNotGavePower)
        if (success) {
          this.httpData = response.data || {}
          this.showForm(this.httpData)
        }
      })
    },
    // 新加一行
    addFee() {
      if (this.model.phoneArr.length <= 3) {
        this.model.phoneArr.push({})
      } else {
        alert('公司服务热线最多添加4个')
      }
    },
    // 删除一行
    delFee(arr, index) {
      if (arr.length <= 1) {
        return
      }
      arr.splice(index, 1)
    },
    // 回填表单
    showForm(data) {
      if (data) {
        this.model.name = data.name
        this.model.communityCode = data.communityCode
        this.model.legalPerson = data.legalPerson
        this.model.contactsName = data.contactsName // 公司联系人
        this.model.contactsPhone = data.contactsPhone // 联系电话
        // 回填服务热线：可能多个字符串--> 转为数组
        let backPhones = dotData(data, 'serviceHotline')
        if (backPhones && typeof backPhones === 'string') {
          let backPhoneArr = backPhones.split(',') // 用逗号分隔成数组
          console.log('backPhoneArr', backPhoneArr)
          this.model.phoneArr = []
          for (let i in backPhoneArr) {
            this.model.phoneArr.push({phone: backPhoneArr[i]})
          }
        }
        // 回填地址
        let addressArr = []
        if (dotData(data, 'provinceNo')) {
          addressArr.push(dotData(data, 'provinceNo'))
          if (dotData(data, 'cityNo')) {
            addressArr.push(dotData(data, 'cityNo'))
            if (dotData(data, 'districtNo')) {
              addressArr.push(dotData(data, 'districtNo'))
            }
          }
        }
        this.model.addressArr = addressArr
        // 详细地址
        this.model.detailAddress = data.detailAddress
        // logo
        if (dotData(data, 'logo')) {
          this.model.logoImg = [dotData(data, 'logo')]
        }
        // 营业执照
        if (dotData(data, 'businessLicense')) {
          this.model.businessImg = [dotData(data, 'businessLicense')]
        }
        // 道路运输图片
        if (dotData(data, 'carriageTestify')) {
          this.model.roadImg = [dotData(data, 'carriageTestify')]
        }
      }
    },
    // 清空表格
    resetFields() {
      this.$refs.companyForm.resetFields()
    },
    emitIsClickEditing() {
      this.$emit('IsClickEditing', true)
    },
    submit() {
      this.$refs.companyForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        let data = copy(this.model, true)
        console.log('this.isNotGavePower', this.isNotGavePower, 'typeof', typeof this.isNotGavePower)
        if (this.isClickEditing) { // 如果从我公司点击进来的，从传递进来data里面取id
          data.id = this.data.id
        } else {
          if (this.isNotGavePower === 2) { // 如果从未完善资质 或 审核不通过页面来的，从httpData里面取id
            data.id = this.httpData.id
          } else if (this.isNotGavePower === 1) { // 若是未授权进来的修改页面，提交时不需要传id，但要传个标识给后端用以区分
            data.isAccredit = 1
            data.userId = this.userId
            data.userPhone = this.userPhone
          }
        }
        // 处理地址
        data.provinceNo = dotData(data.addressArr, '[0]')
        data.cityNo = dotData(data.addressArr, '[1]')
        data.districtNo = dotData(data.addressArr, '[2]')
        delete data.addressArr
        // 处理图片
        data.logo = dotData(data.logoImg, '[0]')
        data.businessLicense = dotData(data.businessImg, '[0]')
        data.carriageTestify = dotData(data.roadImg, '[0]')
        delete data.logoImg
        delete data.businessImg
        delete data.roadImg
        // 处理电话号码
        if (Array.isArray(data.phoneArr)) {
          let tempArr = []
          data.phoneArr.forEach(v => {
            tempArr.push(v.phone)
          })
          data.serviceHotline = tempArr.join(',')
        }
        delete data.phoneArr
        if (this.isTrunkUser === 1) {
          data.isTrunk = 1 // 物流干线的修改 我的公司
        }
        let title = '修改成功'
        let url = '/ms-warehouse-order/company/updateCompany'
        this.loading = true
        let token = getTempToken()
        console.log('再次提交之前: 是否是未授权进来的isNotGavePower', this.isNotGavePower)
        // 1、若是我的公司--点编辑进来的，提交不需要token
        if (this.isClickEditing) {
          this.$ajax.post(url, data).then(response => {
            const success = dotData(response, 'success')
            if (success) {
              this.loading = false
              confirm(title, '提示', {
                type: 'success',
                showCancelButton: false,
                closeOnClickModal: false
              }).finally(_ => {
                // 再次修改提交后退出登录并且跳转到审核中静态页面
                onlyLoginOut()
                window.location.href = '/#/examining'
              })
            } else {
              this.loading = false
            }
          }).catch(_ => {
            this.loading = false
          })
        } else {
          // 2、若是登录审核未通过isTrunk=2 =0未完善、-->进来的单独编辑web，提交时需要token
          console.log('token', token)
          this.$ajax.post(url, data, undefined, {token}).then(response => {
            const success = dotData(response, 'success')
            if (success) {
              this.loading = false
              this.$router.push({path: '/examining'})
            } else {
              this.loading = false
            }
          }).catch(_ => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
